/**
 * $RCSfile: GetCurrentPerson.java,v $
 * $Revision: 1.1 $
 * $Date: 2014/07/08 00:26:16 $
 * <p>
 * Copyright (C) 2003 itjds, Inc. All rights reserved.
 * <p>
 * This software is the proprietary information of itjds, Inc.
 * Use is subject to license terms.
 */
package com.ds.common.org.expression.person;


import com.ds.common.expression.ParseException;
import com.ds.common.expression.function.Function;
import com.ds.org.Person;
import com.ds.org.PersonNotFoundException;
import com.ds.server.JDSClientService;
import com.ds.server.OrgManagerFactory;

import java.util.Map;
import java.util.Stack;

/**
 * <p>
 * Title: JDS系统管理系统
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * </p>
 * <p>
 * Copyright: Copyright (c) 2006
 * </p>
 * <p>
 * Company: www.justdos.net
 * </p>
 *
 * @author lxl
 * @version 1.0
 */
public class GetCurrentPerson extends Function {
    public GetCurrentPerson() {
        numberOfParameters = 1;
    }

    public void run(Stack stack) throws ParseException {
        checkStack(stack); // check the stack

        stack.push(perform(stack.pop()));
    }

    /**
     * @return
     */
    private Person perform(Object o) throws ParseException {
        if (o == null) {
            return null;
        }



        if (o instanceof Map) {
            Map ctx = (Map) o;
            String userId = (String) ctx.get("USERID");
            if (userId == null) {
                return null;
            }
            Person person = null;
            try {
                person = OrgManagerFactory.getOrgManager().getPersonByID(userId);
            } catch (PersonNotFoundException e) {
                throw new ParseException("用户" + userId + "未找到 : " + e);
            }
            return person;
        } else if (o instanceof JDSClientService) {
            JDSClientService client = (JDSClientService) o;

            Person person = null;
            try {
                person = OrgManagerFactory.getOrgManager(client.getConfigCode()).getPersonByID(client.getConnectInfo().getUserID());
            } catch (PersonNotFoundException e) {
                throw new ParseException(e);
            }
            return person;
        } else {
            throw new ParseException("类型不正确，需要Map");
        }


    }

}
